<?php

namespace App\Http\Controllers\Labaicai;

use App\Http\Requests\Labaicai\FooodsRequest;
use App\Http\Resources\Labaicai\FooodsResource;
use App\Models\DailyDiet;
use App\Models\Labaicai\Fooods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;

class FooodsController extends Controller
{
    /**
     * Notes:
     * Created on 2024-02-02 02:59:40
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $query = Fooods::filter();
        return FooodsResource::collection(
            $request->has('page') ? $query->paginate(per()) : $query->get()
        );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(FooodsRequest $request)
    {
        Fooods::create($request->all());
    }

    public function addDiet(Request $request)
    {
        $food = $request->post('food');
        $category = $request->post('category');
        $createdAt = date('Y年') . $request->post('date');
        $createdAt = str_replace(['年', '月', '日'], ['-', '-', ''], $createdAt);
        $data = [
            'category_id' => $category['id'],
            'food_id'     => $food['id'],
            'number'      => $request->post('enterResult'),
            'type'        => $category['type'],
            'created_at'  => $createdAt
        ];
//        Log::info('data ===', $data);
        $result = DailyDiet::insert($data);
        if ($result) {
            return response(['message' => '成功']);
        } else {
            return response(['message' => '失败'], 400);
        }
    }

    /**
     * Notes:
     * Created on 2024-02-02 02:59:40
     * @param $id
     * @return FooodsResource
     */
    public function show($id)
    {
        return FooodsResource::make(Fooods::findOrFail($id));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(FooodsRequest $request, $id)
    {
        Fooods::where('id', $id)->updateFillable($request->all());
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $m = Fooods::findOrFail($id);
        $m->delete();
    }
}
